<template>
  <div class="stream-manage">
    <div class="two-panel-layout">
      <!-- 左侧：流媒体管理 -->
      <StreamServerList class="w-[30%]" :stream-servers="streamStore.streamServers"
        :selected-server="streamStore.selectedServer" :loading="streamStore.loading"
        :has-selected-server="streamStore.hasSelectedServer" @add-server="handleAddServer"
        @edit-server="handleEditServer" @delete-server="handleDeleteServer" @select-server="handleSelectServer" />

      <!-- 右侧：摄像机列表 -->
      <CameraList class="w-[70%]" :camera-list="streamStore.cameraList" :selected-cameras="streamStore.selectedCameras"
        :loading="streamStore.cameraLoading" :has-selected-cameras="streamStore.hasSelectedCameras"
        :page-config="cameraPageConfig" :keyword="cameraSearchKeyword" @refresh="handleRefreshCameraList"
        @open-group-management="handleOpenGroupManagement" @toggle-camera-selection="handleToggleCameraSelection"
        @select-change="handleCameraSelectChange" @play-camera="handlePlayCamera" @search="handleCameraSearch"
        @batch-delete="handleBatchDelete" />
    </div>

    <!-- 服务器管理对话框 -->
    <ServerDialog ref="serverDialogRef" :visible="serverDialogVisible" :is-edit-mode="isEditMode"
      :server-data="currentServerData" @close="handleCloseServerDialog" @save="handleSaveServer"
      @update:visible="serverDialogVisible = $event" />

    <!-- 分组管理对话框 -->
    <GroupManagementDialog ref="groupManagementRef" :visible="groupManagementVisible" :group-list="streamStore.groupList"
      :selected-group="streamStore.selectedGroup" :has-selected-cameras="streamStore.hasSelectedCameras"
      :has-selected-group="streamStore.hasSelectedGroup" @close="handleCloseGroupManagement"
      @move-to-group="handleMoveToGroup" @add-group="handleAddGroup" @edit-group="handleEditGroup"
      @delete-group="handleDeleteGroup" @select-group="handleSelectGroup"
      @camera-selection-change="handleCameraSelectionChange"
      @update:visible="groupManagementVisible = $event" />

    <!-- 分组对话框 -->
    <GroupDialog :visible="groupDialogVisible" :is-edit-mode="isEditGroupMode" :group-data="currentGroupData"
      @close="handleCloseGroupDialog" @save="handleSaveGroup" @refresh="handleRefreshChannelList" @update:visible="groupDialogVisible = $event" />

    <!-- 流播放对话框 -->
    <StreamPlayerDialog :visible="streamPlayerVisible" :camera-data="currentCameraData" :server-data="currentServerData"
      @close="handleCloseStreamPlayer" @update:visible="streamPlayerVisible = $event" />

    <!-- 移动到分组对话框 -->
    <MoveToGroupDialog :visible="moveToGroupVisible" :selected-camera-ids="selectedCameraIds"
      @close="handleCloseMoveToGroup" @confirm="handleMoveToGroupConfirm" @update:visible="moveToGroupVisible = $event" />

    <!-- 密码验证对话框 -->
    <PasswordDialog ref="passwordDialogRef" :visible="passwordDialogVisible"
      @close="handleClosePasswordDialog" @cancel="handleCancelPasswordDialog" @confirm="handleConfirmPassword"
      @update:visible="passwordDialogVisible = $event" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { success, error } from '../../../utils/toast'
import { useStreamStore } from '../../../stores/stream'
import { getAllMenu, $getDeviceList, $deleteDevices } from '../../../api/device'
import type { StreamServer, Device } from '../../../types'

// 导入组件
import StreamServerList from './components/StreamServerList.vue'
import CameraList from './components/CameraList.vue'
import GroupManagementDialog from './components/GroupManagementDialog.vue'
import ServerDialog from './components/ServerDialog.vue'
import GroupDialog from './components/GroupDialog.vue'
import StreamPlayerDialog from './components/StreamPlayerDialog.vue'
import MoveToGroupDialog from './components/MoveToGroupDialog.vue'
import PasswordDialog from '../../../components/PasswordDialog.vue'
import { confirm } from '../../../utils/confirm'
import { getSavedLoginInfo } from '../../../utils/auth'

// 使用store
const streamStore = useStreamStore()

// 组件引用
const serverDialogRef = ref()
const groupManagementRef = ref()
const passwordDialogRef = ref()

// 分页配置
const cameraPageConfig = computed(() => ({
  ...streamStore.cameraPageConfig,
  handleSizeChange: (pageSize: number) => streamStore.handleCameraPageSizeChange(pageSize, cameraSearchKeyword.value),
  handleCurrentChange: (currentPage: number) => streamStore.handleCameraCurrentPageChange(currentPage, cameraSearchKeyword.value)
}))

// 对话框状态
const serverDialogVisible = ref(false)
const groupDialogVisible = ref(false)
const groupManagementVisible = ref(false)
const streamPlayerVisible = ref(false)
const moveToGroupVisible = ref(false)
const passwordDialogVisible = ref(false)
const isEditMode = ref(false)
const isEditGroupMode = ref(false)

// 选中的摄像机ID列表
const selectedCameraIds = ref<string[]>([])

// 摄像机搜索关键词
const cameraSearchKeyword = ref('')

// 当前编辑的数据
const currentServerData = ref<StreamServer | null>(null)
const currentGroupData = ref<{ id: number; name: string } | null>(null)
const currentCameraData = ref<Device | null>(null)

// 待删除的服务器信息
const pendingDeleteServer = ref<StreamServer | null>(null)

// 待删除的摄像机信息
const pendingDeleteCameras = ref<number[]>([])

// 服务器相关事件处理
const handleAddServer = () => {
  isEditMode.value = false
  currentServerData.value = null
  serverDialogVisible.value = true
}

const handleEditServer = () => {
  if (!streamStore.selectedServer || streamStore.selectedServer.id === 'all') return
  isEditMode.value = true
  currentServerData.value = streamStore.selectedServer as StreamServer
  serverDialogVisible.value = true
}

const handleDeleteServer = async () => {
  if (!streamStore.selectedServer || streamStore.selectedServer.id === 'all') return

  try {
    const serverName = streamStore.selectedServer.name || streamStore.selectedServer.ip || '服务器'
    await confirm.delete(serverName, '流媒体服务器')
    
    // 保存待删除的服务器信息
    pendingDeleteServer.value = streamStore.selectedServer as StreamServer
    
    // 显示密码验证对话框
    passwordDialogVisible.value = true
  } catch (err) {
    // 用户取消删除或其他错误
  }
}

const handleSelectServer = async (server: StreamServer | { id: 'all' }) => {
  await streamStore.selectServer(server)
}

const handleCloseServerDialog = () => {
  serverDialogVisible.value = false
  currentServerData.value = null
}

const handleSaveServer = async (data: Partial<StreamServer>) => {
  try {
    if (isEditMode.value) {
      await streamStore.updateStreamServer(data as StreamServer)
      success('更新成功')
    } else {
      await streamStore.addStreamServer({ ...data, type: 1 })
      success('添加成功')
    }
    // 关闭对话框
    serverDialogVisible.value = false
  } finally {
    // 重置 loading 状态
    if (serverDialogRef.value) {
      serverDialogRef.value.resetLoading()
    }
  }
}

// 摄像机相关事件处理
const handleRefreshCameraList = async () => {
  streamStore.cameraLoading = true
  if (streamStore.selectedServer?.id) {
    try {
      await streamStore.refreshDeviceListByServerId(streamStore.selectedServer?.id as number)
      await streamStore.loadCameraList(
        streamStore.selectedServer.id,
        streamStore.cameraPageConfig.currentPage,
        streamStore.cameraPageConfig.pageSize,
        cameraSearchKeyword.value
      )
      success('刷新成功')
    } finally {
      streamStore.cameraLoading = false
    }
  } else {
    error('请先选择服务器')
  }
}

const handleToggleCameraSelection = (cameraId: number) => {
  streamStore.toggleCameraSelection(cameraId)
}

const handleCameraSelectChange = (selectedCameras: number[]) => {
  streamStore.selectedCameras = selectedCameras
}

// 处理摄像机搜索
const handleCameraSearch = async (keyword: string) => {
  cameraSearchKeyword.value = keyword
  
  // 调用API进行搜索
  if (streamStore.selectedServer && streamStore.selectedServer.id !== 'all' && streamStore.selectedServer.id) {
    try {
      await streamStore.loadCameraList(
        streamStore.selectedServer.id,
        1, // 重置到第一页
        streamStore.cameraPageConfig.pageSize,
        keyword
      )
    } catch (err) {
      console.error('搜索摄像机失败:', err)
      error('搜索失败')
    }
  }
}

// 播放摄像机
const handlePlayCamera = (camera: Device) => {
  currentCameraData.value = camera
  currentServerData.value = streamStore.streamServers.find(server => server.id === camera.nvrId) || null
  streamPlayerVisible.value = true
}

// 处理批量删除摄像机
const handleBatchDelete = async (cameraIds: number[]) => {
  if (cameraIds.length === 0) {
    error('请先选择要删除的摄像机')
    return
  }

  try {
    await confirm.delete(`${cameraIds.length}个摄像机`, '摄像机')
    
    // 保存待删除的摄像机ID列表
    pendingDeleteCameras.value = cameraIds
    
    // 显示密码验证对话框
    passwordDialogVisible.value = true
  } catch (err) {
    // 用户取消删除或其他错误
  }
}

// 关闭播放弹框
const handleCloseStreamPlayer = () => {
  streamPlayerVisible.value = false
  currentCameraData.value = null
  currentServerData.value = null
}

const handleOpenGroupManagement = () => {
  groupManagementVisible.value = true
}

// 分组管理相关事件处理
const handleCloseGroupManagement = () => {
  groupManagementVisible.value = false
}

const handleMoveToGroup = () => {
  // 检查是否有选中的摄像机
  if (selectedCameraIds.value.length === 0) {
    error('请先选择要移动的摄像机')
    return
  }
  
  moveToGroupVisible.value = true
}

const handleAddGroup = () => {
  isEditGroupMode.value = false
  currentGroupData.value = null
  groupDialogVisible.value = true
}

const handleEditGroup = () => {
  if (!streamStore.selectedGroup) return
  isEditGroupMode.value = true
  currentGroupData.value = {
    id: streamStore.selectedGroup.id,
    name: streamStore.selectedGroup.name
  }
  groupDialogVisible.value = true
}

const handleDeleteGroup = async () => {
  if (!streamStore.selectedGroup) return

  // 检查是否为根节点
  if (streamStore.selectedGroup.id === 1) {
    error('根节点不允许删除')
    return
  }

  try {
    // 检查分组下是否有子分组或设备
    const hasChildren = await checkGroupHasChildren(streamStore.selectedGroup.id)
    if (hasChildren) {
      error('该分组下存在分组或摄像机，不允许删除！')
      return
    }

    await confirm.delete(streamStore.selectedGroup.name, '分组')

    await streamStore.deleteGroup(streamStore.selectedGroup.id)
    success('删除成功')
    
    // 删除成功后刷新通道列表
    await handleRefreshChannelList()
  } catch (err) {
    // 用户取消删除或其他错误
  }
}

const handleSelectGroup = (group: any) => {
  streamStore.selectGroup(group)
}

// 处理摄像机选择变化
const handleCameraSelectionChange = (selectedCameras: any[]) => {
  // 更新选中的摄像机ID列表
  selectedCameraIds.value = selectedCameras.map(camera => camera.id)
}

const handleCloseGroupDialog = () => {
  groupDialogVisible.value = false
  currentGroupData.value = null
}

const handleSaveGroup = async (data: { id?: number; name: string; parentId?: number }) => {
  try {
    if (isEditGroupMode.value) {
      await streamStore.updateGroup(data as { id: number; name: string })
      success('更新成功')
    } else {
      await streamStore.addGroup(data)
      success('添加成功')
    }
    groupDialogVisible.value = false
  } catch (err) {
    error('保存失败')
  }
}

// 检查分组下是否有子分组或设备
const checkGroupHasChildren = async (groupId: number): Promise<boolean> => {
  try {
    // 获取所有菜单数据
    const menuResponse = await getAllMenu()
    const allMenus = menuResponse.data || []
    
    // 检查是否有子分组
    const hasSubGroups = allMenus.some((menu: any) => menu.parentId === groupId)
    if (hasSubGroups) {
      return true
    }
    
    // 检查是否有设备
    const deviceResponse = await $getDeviceList(groupId.toString())
    const devices = deviceResponse.data || []
    if (devices.length > 0) {
      return true
    }
    
    return false
  } catch (err) {
    console.error('检查分组子项失败:', err)
    // 如果检查失败，为了安全起见，不允许删除
    return true
  }
}

// 移动分组相关事件处理
const handleCloseMoveToGroup = () => {
  moveToGroupVisible.value = false
}

const handleMoveToGroupConfirm = async (targetGroupId: number) => {
  try {
    // 将选中的摄像机ID转换为数字数组
    const cameraIds = selectedCameraIds.value
      .filter(id => id.startsWith('camera_'))
      .map(id => parseInt(id.replace('camera_', '')))
    
    if (cameraIds.length === 0) {
      error('没有有效的摄像机ID')
      return
    }
    
    // 调用移动API
    await streamStore.moveCamerasToGroup(cameraIds, targetGroupId)
    success(`已将 ${cameraIds.length} 个摄像机移动到目标分组`)
    
    // 关闭弹框并刷新数据
    moveToGroupVisible.value = false
    await handleRefreshChannelList()
  } catch (err) {
    console.error('移动摄像机失败:', err)
    error('移动失败')
  }
}

// 刷新通道列表
const handleRefreshChannelList = async () => {
  try {
    // 刷新通道树数据
    if (groupManagementRef.value && groupManagementRef.value.refreshChannelTree) {
      await groupManagementRef.value.refreshChannelTree()
    }
    success('数据已刷新')
  } catch (err) {
    console.error('刷新通道列表失败:', err)
    error('刷新失败')
  }
}

// 密码验证对话框相关事件处理
const handleClosePasswordDialog = () => {
  passwordDialogVisible.value = false
  pendingDeleteServer.value = null
  pendingDeleteCameras.value = []
}

const handleCancelPasswordDialog = () => {
  passwordDialogVisible.value = false
  pendingDeleteServer.value = null
  pendingDeleteCameras.value = []
}

const handleConfirmPassword = async (password: string) => {
  if (!pendingDeleteServer.value && pendingDeleteCameras.value.length === 0) return
  
  try {
    // 这里应该调用验证密码的API
    // 暂时模拟密码验证逻辑，实际项目中需要调用后端API
    const isValidPassword = await validatePassword(password)
    
    if (isValidPassword) {
      // 密码验证成功，执行删除操作
      if (pendingDeleteServer.value) {
        // 删除服务器
        await streamStore.deleteStreamServer(pendingDeleteServer.value.id as number)
        success('删除成功')
      } else if (pendingDeleteCameras.value.length > 0) {
        // 批量删除摄像机
        await $deleteDevices(pendingDeleteCameras.value)
        success(`成功删除 ${pendingDeleteCameras.value.length} 个摄像机`)
        
        // 刷新摄像机列表
        await handleRefreshCameraList()
        
        // 清除选中状态
        streamStore.selectedCameras = []
      }
      
      // 关闭密码对话框
      passwordDialogVisible.value = false
      pendingDeleteServer.value = null
      pendingDeleteCameras.value = []
    } else {
      // 密码验证失败
      if (passwordDialogRef.value) {
        passwordDialogRef.value.setError('密码错误，请重新输入')
      }
    }
  } catch (err) {
    console.error('删除失败:', err)
    error('删除失败')
    
    // 关闭密码对话框
    passwordDialogVisible.value = false
    pendingDeleteServer.value = null
    pendingDeleteCameras.value = []
  }
}

// 验证密码的函数 - 与登录时保存的密码进行对比
const validatePassword = async (inputPassword: string): Promise<boolean> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      try {
        // 获取保存的登录信息
        const savedLoginInfo = getSavedLoginInfo()
        
        if (savedLoginInfo && savedLoginInfo.password) {
          // 对比用户输入的密码与保存的密码（当前会话或记住的密码）
          const isValid = inputPassword === savedLoginInfo.password
          resolve(isValid)
        } else {
          // 理论上不应该到达这里，因为现在总是会保存当前会话的密码
          // 如果确实没有密码信息，可能是系统异常或用户未登录
          console.warn('没有找到保存的密码信息，可能是系统异常')
          resolve(false)
        }
      } catch (error) {
        console.error('密码验证失败:', error)
        resolve(false)
      }
    }, 500)
  })
}

// 组件挂载时加载数据
onMounted(() => {
  streamStore.loadStreamServers()
})
</script>

<style scoped>
.stream-manage {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 20px;
  flex-shrink: 0;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-description {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.two-panel-layout {
  display: flex;
  flex: 1;
  gap: 16px;
  height: calc(100% - 120px);
}
</style>